package com.xianzw.mnfun.task;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import com.xianzw.mnfun.model.domain.TouTiao;
import com.xianzw.mnfun.service.TouTiaoService;
import com.xianzw.mnfun.utils.DataServiceUtil;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

/**
 * 头条任务
 * @author xianzw
 *
 * 2018年9月11日下午5:14:24
 */
@Component
public class TouTiaoTask{

    //配置您申请的KEY
    public static final String APPKEY ="bfbfe90200f36f6477eb6f2ec89dd433";
    
    @Autowired
    private TouTiaoService touTiaoService;
    
    //1.运势查询
    @SuppressWarnings({ "unchecked", "rawtypes" })
    @Scheduled(cron = "0 5/15 0-23 * * *")
    public void getRequest(){
        String result =null;
        String url ="http://v.juhe.cn/toutiao/index";//请求接口地址
        Map params = new HashMap();//请求参数
            params.put("key",APPKEY);//应用APPKEY(应用详细页查询)
            params.put("type","top");//类型：top(头条，默认),shehui(社会),guonei(国内),guoji(国际),yule(娱乐),tiyu(体育)junshi(军事),keji(科技),caijing(财经),shishang(时尚)
 
        try {
            result =DataServiceUtil.net(url, params, "GET");
            JSONObject object = JSONObject.fromObject(result);
            
            if(object.getInt("error_code")==0){
        	 JSONObject resultObject = JSONObject.fromObject(object.get("result"));
        	 JSONArray jsonArray = JSONArray.fromObject(resultObject.get("data"));
        	 List<TouTiao> touTiaoList = (List<TouTiao>)JSONArray.toCollection(jsonArray, TouTiao.class);
        	 if(touTiaoList!=null) {
        	     for (TouTiao touTiao : touTiaoList) {
        		 
        		 List<TouTiao> touTiaos = touTiaoService.findByUniquekey(touTiao.getUniquekey());
        		 if(touTiaos.isEmpty()) {
        		     touTiaoService.saveByTouTiao(touTiao);
        		 }
        	     }
        	 }
                System.out.println(object.get("result"));
            }else{
                System.out.println(object.get("error_code")+":"+object.get("reason"));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
